<template>
  <div class="app-container">
    <div class="app-container__section">
      <PlusSearch v-bind="getSearchBinds()" :columns="columns" v-model="searchForm">
        <template #plus-field-createTime>
          <el-date-picker start-placeholder="开始时间" end-placeholder="结束时间" v-model="searchForm.timeRange" type="daterange" />
        </template>
      </PlusSearch>
    </div>

    <div class="app-container__section">
      <PlusTable v-bind="getBinds()" :columns="columns">
        <template #empty>
          <el-empty :image-size="100" description="暂无学校数据"></el-empty>
        </template>
        <template #title>
          <table-title />
        </template>
        <template #toolbar>
          <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['edutation:school:add']">新增</el-button>
          <el-button type="success" plain icon="Edit" :disabled="gSelection.length !== 1" @click="handleUpdate" v-hasPermi="['edutation:school:edit']">修改</el-button>
          <el-button type="danger" plain icon="Delete" :disabled="gSelection.length === 0" @click="handleDelete" v-hasPermi="['edutation:school:remove']">删除</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['edutation:school:export']">导出</el-button>

          <ClockTimer :task="gGetList" />
          <SearchAreaControl v-model="gShowSearchForm" />
        </template>

        <template #plus-cell-logo="{ row }">
          <image-preview :src="row.logo" />
        </template>

        <template #plus-cell-action="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['edutation:school:edit']">修改</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['edutation:school:remove']">删除</el-button>
        </template>
      </PlusTable>
    </div>

    <PlusDialogForm
      ref="plusFormInstance"
      v-model:visible="dialogShow"
      v-model="formData"
      :form="{ columns, labelWidth: '110px', labelPosition: 'right', rules: formRules }"
      :dialog="{ title: dialogTitle, width: '540px', top: '12vh', confirmLoading }"
      @confirm="handleSubmit"
      @cancel="handleCancel"
    >
      <template #plus-field-logo>
        <image-upload v-model="formData.logo" />
      </template>
    </PlusDialogForm>
  </div>
</template>

<script setup name="School">
import { listSchoolApi, getSchoolApi, delSchoolApi, addSchoolApi, updateSchoolApi } from '@/api/edutation/school'
import { useTablePage } from '@/hooks/useTablePage.js'
import { useActions } from '@/hooks/useActions.js'
import { getCurrentInstance, ref } from 'vue'
const { proxy } = getCurrentInstance()

const primaryKey = 'schoolId' // 主键

// =============================================
const plusFormInstance = ref(null)
const formInstance = computed(() => plusFormInstance.value?.formInstance)
const state = reactive({
  dialogShow: false,
  formData: {
    status: '',
    createBy: '',
    createTime: '',
    updateBy: '',
    updateTime: '',
    remark: '',
    schoolCode: '',
    logo: '',
    contactName: '',
    contactPhone: '',
    schoolName: ''
  },
  formRules: {
    schoolCode: [{ required: true, message: '学校编码不能为空', trigger: ['blur'] }],
    contactName: [{ required: true, message: '联系人不能为空', trigger: ['blur'] }],
    contactPhone: [
      { required: true, message: '联系电话不能为空', trigger: ['blur'] },
      { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号', trigger: ['blur'] }
    ],
    schoolName: [{ required: true, message: '学校编码不能为空', trigger: ['blur'] }]
  },
  confirmLoading: false
})
const { formData, confirmLoading, formRules, dialogShow } = toRefs(state)
const isEdit = computed(() => !!formData.value[primaryKey])
const dialogTitle = computed(() => (isEdit.value ? '编辑' : '新增') + '学校')

// =============================================
const columns = computed(() => [
  {
    label: '学校名称',
    prop: 'schoolName',
    hideInSearch: false,
    hideInTable: false,
    hideInForm: false,
    valueType: 'input',
    fieldProps: {
      modelModifiers: { trim: true }
    },
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '学校编码',
    prop: 'schoolCode',
    hideInSearch: false,
    hideInTable: false,
    hideInForm: false,
    valueType: 'input',
    fieldProps: {
      modelModifiers: { trim: true }
    },
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '学校Logo',
    prop: 'logo',
    hideInSearch: true,
    hideInTable: false,
    hideInForm: false,
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '联系人',
    prop: 'contactName',
    hideInSearch: false,
    hideInTable: false,
    hideInForm: false,
    valueType: 'input',
    fieldProps: {
      modelModifiers: { trim: true }
    },
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '联系电话',
    prop: 'contactPhone',
    hideInSearch: false,
    hideInTable: false,
    hideInForm: false,
    valueType: 'input',
    fieldProps: {
      modelModifiers: { trim: true }
    },
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '备注',
    prop: 'remark',
    hideInSearch: true,
    hideInTable: false,
    hideInForm: false,
    valueType: 'textarea',
    fieldProps: {
      modelModifiers: { trim: true }
    },
    tableColumnProps: {
      align: 'center'
    }
  },
  {
    label: '创建时间',
    prop: 'createTime',
    hideInSearch: false,
    hideInTable: false,
    hideInForm: true,
    valueType: 'date-picker',
    tableColumnProps: {
      align: 'center'
    },
    fieldProps: {
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD'
    }
  },
  {
    label: '创建者',
    prop: 'createBy',
    hideInSearch: true,
    hideInTable: false,
    hideInForm: true,
    tableColumnProps: {
      align: 'center'
    },
    valueType: 'input'
  },
  {
    label: '操作',
    prop: 'action',
    minWidth: '100px',
    hideInSearch: true,
    hideInForm: true,
    tableColumnProps: {
      align: 'center',
      fixed: 'right'
    }
  }
])

// =============================================
// 列表请求逻辑
const searchForm = ref({})
const { gGetList, gSelection, gShowSearchForm, getBinds, getSearchBinds } = useTablePage(listSchoolApi, {
  searchForm,
  beforeRequest(query) {
    const { timeRange, ...rest } = query
    const params = proxy.formatRangeTime(timeRange, undefined, 'YYYY-MM-DD')
    return { ...rest, params }
  }
})

// 删除逻辑
const { deleteAction } = useActions()
function handleDelete(row) {
  deleteAction({
    api: delSchoolApi,
    uniqueKey: primaryKey,
    selection: row[primaryKey] || gSelection.value
  }).then(() => {
    gGetList()
  })
}

// 新增操作
const handleAdd = () => {
  dialogShow.value = true
}

// 取消按钮操作
function handleCancel() {
  dialogShow.value = false
  formData.value = {}
  formInstance.value.resetFields()
}

// 确定按钮操作
const handleSubmit = async () => {
  try {
    confirmLoading.value = true
    if (isEdit.value) {
      await updateSchoolApi(formData.value)
      proxy.$modal.msgSuccess('修改成功')
    } else {
      await addSchoolApi(formData.value)
      proxy.$modal.msgSuccess('新增成功')
    }
    handleCancel()
    await gGetList()
  } catch (error) {
    console.warn('提交错误:', error)
  } finally {
    confirmLoading.value = false
  }
}

// 修改回显数据操作
function handleUpdate(row) {
  const key = row[primaryKey] || gSelection.value[0][primaryKey]
  getSchoolApi(key).then((response) => {
    formData.value = response.data
    dialogShow.value = true
  })
}

// 导出逻辑
const handleExport = () => {
  proxy.download('edutation/school/export', { ...searchForm.value }, `school_${new Date().getTime()}.xlsx`)
}
</script>
